﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using MySql.Data.MySqlClient;
using System.Text;
using System.Data;

namespace TKWeb
{
	public partial class RecData : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			byte[] buffer = Request.BinaryRead(Request.TotalBytes);
			string strXml = System.Text.Encoding.UTF8.GetString(buffer);
			if (string.IsNullOrEmpty(strXml))
			{
				return;
			}
			XmlDocument doc = new XmlDocument();
			doc.LoadXml(strXml);

			MySqlTransaction tran = null;
			DataTable dt = null;
			DataRow dr = null;
			string title = string.Empty;
			string propValue = string.Empty;
			string props= string.Empty;
			int objId = 0;
			object objDBValue = string.Empty;
			int cid = 0;
			string value = null;
			try
			{
				int fileId = Convert.ToInt32(doc.DocumentElement.Attributes["fileid"].Value);
				string url = doc.DocumentElement.Attributes["url"].Value;
				int hash = (url + "$" + fileId).GetHashCode();

				dt = Global.DBAccess.GetTable("select file_id,obj_id from crawl_data_map where hash=@hash", new MySqlParameter[] { new MySqlParameter("hash", hash) });
				if (dt.Rows.Count > 0)
				{
					dr = dt.Rows[0];
					objId = Convert.ToInt32(dr["obj_id"]);
					dt = Global.DBAccess.GetTable("select props,cid from obj_info where obj_id=@obj_id",new MySqlParameter[]{ new MySqlParameter("obj_id", objId)});
					if (dt.Rows.Count > 0)
					{
						dr = dt.Rows[0];
						props = dr["props"].ToString();
						cid = Convert.ToInt32(dr["cid"]);
					}
				}

				
			
				StringBuilder sbProp = new StringBuilder();
				tran = Global.DBAccess.BeginTransaction();

				//删除原对象属性值
				if (objId > 0 && !string.IsNullOrEmpty(props))
				{
					string[] arr1 = props.Split(';');
					string[] arr2 = null;
					foreach (string s1 in arr1)
					{
						arr2 = s1.Split(':');
						dt = Global.DBAccess.GetTable("select * from obj_cat_prop where cid=@cid and pid=@pid and parent_pId=0 and parent_vId=0", new MySqlParameter[]{
							new MySqlParameter("cid", cid),
							new MySqlParameter("pid", arr2[0])
						});

						if (dt.Rows.Count > 0)
						{
							dr = dt.Rows[0];
							int dataType = Convert.ToInt32(dr["data_type"]);
							if (dataType == 2)
							{
								Global.DBAccess.ExecuteNonQuery(tran.Connection, "delete from obj_propvalue_lib where vid=@vid", new MySqlParameter("vid", arr2[1]));
							}

							if (dataType == 3)
							{
								Global.DBAccess.ExecuteNonQuery(tran.Connection, "delete from obj_propvalue_text where vid=@vid", new MySqlParameter("vid", arr2[1]));
							}
						}
					}
				}

				foreach (XmlNode n in doc.DocumentElement.ChildNodes)
				{
					value = n.InnerText.Trim();
					if (string.IsNullOrEmpty(value))
					{
						continue;
					}

					if (n.Name.ToLower() == "title")
					{
						title = n.InnerText;
					}

					dt = Global.DBAccess.GetTable("select * from obj_cat_prop where cat_pid in (select cat_pid from crawl_file_field_map where field_id=@field_id)", new MySqlParameter[]{
						new MySqlParameter("field_id", n.Attributes["id"].Value)
					});

					if (dt.Rows.Count > 0)
					{
						int vid = 0;
						dr = dt.Rows[0];
						int dataType = Convert.ToInt32(dr["data_type"]);
						cid = Convert.ToInt32(dr["cid"]);
						int pid = Convert.ToInt32(dr["pid"]);
						
						if (dataType == 1)
						{
							objDBValue = Global.DBAccess.ExecuteScalar(tran.Connection, "select vid from obj_propvalue where name=@name", new MySqlParameter("name", value));
							if (objDBValue != null && objDBValue != DBNull.Value)
							{
								vid = Convert.ToInt32(objDBValue);
							}
							else
							{
								vid = (int)Global.DBAccess.InsertData(tran.Connection, "insert into obj_propvalue(name) values(@name)", new MySqlParameter[] { new MySqlParameter("name", value) });
							}
						}
						else if (dataType == 2)
						{
							vid = (int)Global.DBAccess.InsertData(tran.Connection, "insert into obj_propvalue_text(text) values(@text)", new MySqlParameter[] { new MySqlParameter("text", value) });
						}
						else if (dataType == 3)
						{
							vid = (int)Global.DBAccess.InsertData(tran.Connection, "insert into obj_propvalue_lib(type,link,size,created) values(1,@link,0,sysdate())", new MySqlParameter[] { new MySqlParameter("link", value) });
						}

						if (vid > 0)
						{
							if (sbProp.Length > 0)
							{
								sbProp.Append(";");
							}
							sbProp.AppendFormat("{0}:{1}", pid, vid);
						}
					}
				}

				props = sbProp.ToString();

				if (objId > 0)
				{
					Global.DBAccess.ExecuteNonQuery(tran.Connection, "update obj_info set title=@title,props=@props,modified=sysdate() where obj_id=@obj_id",
						new MySqlParameter("title", title),
						new MySqlParameter("props", props),
						new MySqlParameter("obj_id", objId)
					);
				}
				else
				{
					objId = (int)Global.DBAccess.InsertData(tran.Connection, "insert into obj_info(cid,title,props,created,modified) values(@cid,@title,@props,sysdate(),sysdate())",
						new MySqlParameter[]{
						new MySqlParameter("title", title),
						new MySqlParameter("props", props),
						new MySqlParameter("cid", cid)
						}
					);
					Global.DBAccess.ExecuteNonQuery(tran.Connection, "insert into crawl_data_map(hash,file_id,obj_id,url) values(@hash,@file_id,@obj_id,@url)", 
						new MySqlParameter("hash", hash),
						new MySqlParameter("file_id", fileId),
						new MySqlParameter("obj_id", objId),
						new MySqlParameter("url", url)
						);
				}

				tran.Commit();
				Response.Write("success");
			}
			catch (Exception ex)
			{
				if (tran != null)
				{
					tran.Rollback();
				}
				Response.Write(ex.ToString());
			}
			finally
			{
				if (tran != null)
				{
					tran.Connection.Close();
				}
			}
		}
	}
}